<?php
/**
 * Created by PhpStorm.
 * User: kongjg
 * Date: 16/8/7
 * Time: 下午7:06
 */

require_once("SimpleRest.php");

require_once("labels.php");


class SiteRestHandler extends SimpleRest {
//    获取labels类
    function getLabels(){
        $label = new labels();
        $fileName = $label->getFileName();
        if(file_exists($fileName)){


            $fileArray = file($fileName);
            $rawData = $label->get($fileArray);

            if(empty($rawData)) {
                $statusCode = 404;
                $rawData = array('error' => 'No sites found!');
            } else {
                $statusCode = 200;
            }

            $requestContentType = $_SERVER['HTTP_ACCEPT'];
            $this ->setHttpHeaders($requestContentType, $statusCode);

//        restful返回JSON
            $response = $this->encodeJson($rawData);//json
            $response = str_replace('\n','',$response);
            $response = stripslashes($response);//delete '\'
            $response = str_replace('"{','{',$response);
            $response = str_replace('}"','}',$response);

//        echo "<div> <script> var x = JSON.stringify($response,null,4);document.querySelector('div').innerHTML = x; </script></div>";
            echo $response;

////        可选择返回数据类型
//        if(strpos($requestContentType,'application/json') !== false){
//            $response = $this->encodeJson($rawData);
//            echo $response;
//        } else if(strpos($requestContentType,'text/html') !== false){
//            $response = $this->encodeHtml($rawData);
//            echo $response;
//        } else if(strpos($requestContentType,'application/xml') !== false){
//            $response = $this->encodeXml($rawData);
//            echo $response;
//        }
        }else{
            echo 'no source,please add something.';
        }
    }
    //添加labels类
    function postLabels($id,$title,$desc){
        $label = new labels();
        $label->post($id,$title,$desc);
    }

    public function encodeHtml($responseData) {

        $htmlResponse = "<table border='1'>";
        foreach($responseData as $key=>$value) {
            $htmlResponse .= "<tr><td>". $key. "</td><td>". $value. "</td></tr>";
        }
        $htmlResponse .= "</table>";
        return $htmlResponse;
    }

    public function encodeJson($responseData) {
        $jsonResponse = json_encode($responseData);
        return $jsonResponse;
    }

    public function encodeXml($responseData) {
        // 创建 SimpleXMLElement 对象
        $xml = new SimpleXMLElement('<?xml version="1.0"?><site></site>');
        foreach($responseData as $key=>$value) {
            $xml->addChild($key, $value);
        }
        return $xml->asXML();
    }


}

?>